<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      @click-left="$router.back()"
      title="黑马头条"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="isLoading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->
      <!-- 加载完成-文章详情 -->
      <div v-else-if="article.art_id" class="article-detail">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | dateFormat }}}
          </div>
        </van-cell>
        <follow v-model="article.is_followed" :aut_id="article.aut_id"></follow>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          ref="content"
          class="article-content markdown-body"
          v-html="article.content"
        ></div>
        <van-divider>正文结束</van-divider>
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div v-else-if="errStatus === 404" class="error-wrap">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div v-else class="error-wrap">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->

      <!-- 评论列表 -->
      <commentlist
        :art_id="articleId"
        @total_count="totalcount = $event"
        :commentList="commentList"
      ></commentlist>
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="show = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :badge="totalcount" color="#777" />
      <van-icon
        color="#777"
        name="star-o"
        @click="triggercollect()"
        :style="{
          color: this.article.is_collected === true ? '#FFB6C1' : '#777777'
        }"
      />
      <van-icon
        color="#777"
        name="good-job-o"
        @click="triggerlike()"
        :style="{
          color: this.article.attitude === 1 ? '#FFB6C1' : '#777777'
        }"
      />
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- /底部区域 -->
    <!-- 写评论弹出层 -->
    <van-popup
      position="bottom"
      v-model="show"
      :style="{ height: '30%' }"
      closeable
    >
      <pubcomment
        :articleId="articleId"
        @updatecomment="updaterows($event)"
      ></pubcomment>
    </van-popup>
  </div>
</template>

<script>
import pubcomment from '@/views/article/components/pubcomment.vue'
import {
  getArticle,
  addCollect,
  deleteCollect,
  addLike,
  deleteLike
} from '@/api/article.js'
import commentlist from '@/views/home/components/comment-list.vue'
import follow from '@/components/followed'
import { ImagePreview } from 'vant'
export default {
  props: ['articleId'],
  // 定义属性
  data() {
    return {
      article: {},
      imgList: [], // 图片列表
      isLoading: true, // 页面加载
      errStatus: 200, // 控制错误页面状态
      isFollowLoading: false, // 控制关注按钮的加载状态
      totalcount: 0, // 评论总数小红点
      show: false, //控制添加评论弹出层
      commentList: [] // 控制评论列表，新增评论
    }
  },
  components: {
    commentlist,
    follow,
    pubcomment
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    async getArticleDetail() {
      try {
        const res = await getArticle(this.articleId) // 请求具体文章内容
        this.article = res.data.data
        setTimeout(() => {
          this.getimagepreview()
        }, 10) // 因为数据更新需要时间，所以延迟加载图片
        this.isLoading = false
      } catch (err) {
        console.log(err)
        this.isLoading = false
        // 资源不存在
        if (err.response && err.response === 404) {
          this.errStatus = 404
        }
      }
    },
    getimagepreview() {
      const content = this.$refs.content // 获取到文章内容的DOM
      const list = content.querySelectorAll('img') // 拿到所有图片
      //foreach循环添加图片，并绑定图片预览
      list.forEach((item, index) => {
        this.imgList.push(item.src)
        item.onclick = () => {
          ImagePreview({
            images: this.imgList,
            startPosition: index
          })
        }
      })
    },
    // 收藏开关
    async triggercollect() {
      try {
        if (this.article.is_collected === false) {
          const res = await addCollect(this.articleId) // 发送添加收藏请求
          console.log(res)
          this.$toast.success('收藏成功！')
        } else {
          const res = await deleteCollect(this.articleId) // 发送取消收藏请求
          console.log(res)
          this.$toast.success('取消收藏成功！')
        }
        this.article.is_collected = !this.article.is_collected
      } catch (err) {
        console.log(err)
        this.$toast.fail('收藏失败！')
      }
    },
    // 点赞开关
    async triggerlike() {
      try {
        if (this.article.attitude === -1) {
          const res = await addLike(this.articleId) // 发送添加收藏请求
          console.log(res)
          this.$toast.success('点赞成功！')
          this.article.attitude = 1
        } else {
          const res = await deleteLike(this.articleId) // 发送取消收藏请求
          console.log(res)
          this.$toast.success('取消点赞成功！')
          this.article.attitude = -1
        }
      } catch (err) {
        console.log(err)
        this.$toast.fail('收藏失败！')
      }
    },
    // 新增评论
    updaterows(row) {
      this.commentList.unshift(row) // 插上新元素
      this.show = false //关闭弹出层
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getArticleDetail()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {}
}
</script>

<style lang="less">
@import url('./github-markdown.css');
.article-container {
  text-align: left;
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      } // 清除label插槽上边距
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }
}
</style>
